var myApp = angular.module('myApp',['ngCookies']);


// myApp.value('test','testvalue')

myApp.config(function($sceDelegateProvider) {
    $sceDelegateProvider.resourceUrlWhitelist([
        // Allow same origin resource loads.
        'self',
        'http://localhost:3000/**',
        'https://cncmonitor.top/**',
        'https://www.cncmonitor.top/**'
        // // Allow loading from our assets domain.  Notice the difference between * and **.
        // 'http://cncmonitor.top/**'
    ]);
});

myApp.controller('FaultsController',['$scope','$http','$location','$interval','$window','$cookieStore',function ($scope,$http,$location,$interval,$window,$cookieStore) {
    console.log('FaultsController loaded');


// 播放器 src
    $scope.getMovieSrc = function (videoId) {
        return 'https://cncmonitor.top/movieUploads/' + videoId;

    };


    $scope.getHistoryData = function () {
        var id = $cookieStore.get("faultId");
        var faultId = id.replace("\"","").replace("\"","");
        $http.get('../api/dataHistory/'+ faultId).success(function (response) {

            console.log(response);


        });
    }


    $scope.doInit = function () {
        //配置
        $scope.count = 0;
        $scope.p_pernum = 7;

        //变量
        $scope.p_current = 1;
        $scope.p_all_page =0;
        $scope.pages = [];
        $scope.allFaults = [];
        // $scope.getHistoryData();
    }

    $scope.doInit();


    //首页
    $scope.p_index = function(){
        $scope.load_page(1);
    }
    //尾页
    $scope.p_last = function(){
        $scope.load_page($scope.p_all_page);
    }
    //加载某一页
    $scope.load_page = function(page){
        $scope.p_current = page;
    };
    //初始化页码
   var reloadPno = function(){


        //分页算法
        for(var i = 1; i <= $scope.p_all_page; i++) {
            if(i == 2 && $scope.p_current - 6 > 1) {
                i = $scope.p_current - 6;
            }else if(i == $scope.p_current + 6 && $scope.p_current + 6 < $scope.p_all_page) {
                i = $scope.p_all_page - 1;
            }else{
                $scope.pages.push(i);
            }
        }
    };



    $scope.getFaults = function () {
        $http.get('../api/faults').success(function (response) {
            console.log(response);

            $scope.faults = response.reverse();

            $scope.count = $scope.faults.length;
            $scope.p_current = 1;


            for(var i=0;i<$scope.count ;i+=$scope.p_pernum){
                $scope.allFaults.push($scope.faults.slice(i,i+$scope.p_pernum))
            }

            $scope.p_all_page = $scope.allFaults.length;

            reloadPno();
        });
    }

    // $scope.getFaults();




    $scope.getFault = function () {
        // console.log(sss)
        var id = $cookieStore.get("faultId");
        var faultId = id.replace("\"","").replace("\"","");

        $http.get('../api/faults/' + faultId).success(function (response) {
            $scope.fault = response;
            console.log($scope.fault);

            $("#progress").val(response.progress*100);

        });


        // $scope.getHistoryData();

    };



    //文件下载
    $scope.downloadFile = function (fileSaveName,fileDownloadName) {
        // $http.get('../file/'+fileSaveName).success(function (res) {
        //     console.log(res);
        // });

        window.location.href = "../file/?"+"fileName="+fileSaveName + "&fileDownloadName="+fileDownloadName;

    };



    $scope.setFaultId = function (_id) {
        // $scope.test = test;
        console.log(_id)
        $cookieStore.put("faultId", _id);
        window.location.href = 'project_detail.html#tab-1'

    }

    //编辑故障跳转
    $scope.editFault = function (_id) {
        console.log("editID  " + _id);
        $cookieStore.put("editFaultId",_id);
        window.location.href = 'editFault.html';
    }

    $scope.setFaultIdToDelete = function (_id,index) {
        console.log("需要删除id "+_id);
        $cookieStore.put("deleteFaultId", _id);

        $scope.toDeleteFault = $scope.allFaults[$scope.p_current-1][index];

    }



    $scope.mykey = function (e) {
        var keycode = window.event ? e.keyCode : e.which;//获取按键编码
        if (keycode == 13) {
            $scope.findFault();//如果等于回车键编码执行方法
        }
    }

    $scope.findFault = function () {


        $http.post('../api/find/',$scope.find).success(function (response) {
            $scope.doInit();
            console.log(response);
            $scope.faults = response;
            $scope.allFaults = [];

            $scope.count = $scope.faults.length;
            $scope.p_current = 1;

            for(var i=0;i<$scope.count ;i+=$scope.p_pernum){
                $scope.allFaults.push($scope.faults.slice(i,i+$scope.p_pernum))
            }

            $scope.p_all_page = $scope.allFaults.length;
            // $scope.doInit();
            reloadPno();

        });

        // console.log($("#beginTime").val());
    };


    $scope.addFault = function () {


        // $scope.fault.imageName = $scope.imageName;
        console.log($scope.fault);

        // $http.post('../api/faults/',$scope.fault).success(function (response) {
        //     // window.location.href='#/faults';
        // });
    }


    $scope.uploadFaultImage = function (_id) {
        $cookieStore.put("faultId",_id);
        window.location.href = "form_webuploader.html";
    };






    $("#addFault").click(function(){
        //注册按钮的事件，用ajax提交表单
        $.post("/api/faults",{
            "title" : $("#title").val(),
            "number" : $("#number").val(),
            "factory" : $("#factory").val(),
            "machine_type" : $("#machine_type").val(),
            "location" : $("#location").val(),
            "level" : $scope.fault.level,
            "occur_date" : $("#occur_date").val(),
            "description" : $("#description").val(),
            "manu_man_name" : $("#manu_man_name").val(),
            "manu_man_email" : $("#manu_man_email").val(),
            "manu_man_tel" : $("#manu_man_tel").val()


        },function(result){
            console.log(result);
            $cookieStore.put("faultId",result._id);
            window.location.href = "form_webuploader.html";
        });
    });



    //form












    //
    // $scope.getFault = function () {
    //     var id = $routeParams.id;
    //
    //     $http.get('api/faults/' + id).success(function (response) {
    //         $scope.fault = response;
    //     });
    // }
    //
    //
    // $scope.addFault = function () {
    //
    //     $scope.fault.imageName = $scope.imageName;
    //
    //     $http.post('api/faults/',$scope.fault).success(function (response) {
    //         window.location.href='#/faults';
    //     });
    // }
    //
    //
    // $scope.updateFault = function () {
    //     var id = $routeParams.id;
    //     $scope.fault.imageName = $scope.imageName;
    //
    //     $http.put('api/faults/'+id,$scope.fault).success(function (response) {
    //         window.location.href='#/faults';
    //     });
    // }
    //
    $scope.removeFault = function (id) {
        $http.delete('../api/faults/'+id).success(function (response) {
            console.log("will delte " + id);

            $scope.doInit();
            $scope.getFaults();
        });
    }
    // $scope.isCollapsed = true;
    //
    //
    // $scope.dataReceiving = false;

    //故障诊断添加
    $("#subDiag").click(function () {

        if ($("#diagTitle").val() == ''){
            alert('请停写故障诊断,再提交');
            return;
        }

        if ($("#diagText").val() == ''){
            alert('请停写故障诊断,再提交');
            return;
        }

        $.post("/api/diag",{

            "title":$("#diagTitle").val(),
            "diagText":$("#diagText").val(),
            "progress":$("#progress").val(),
            "faultId":Cookies.get('faultId')


        },function(result){
            console.log("addDiagSuccess")
            $scope.getFault();
            $("#diagTitle").val('');
            $("#diagText").val('');

        });
    });



    //获取传感器数据
    var requestData = function () {
        $http.get('/datalist').success(function (response) {

            if (response.data1.length > 0){
                console.log("I get the data");
                $scope.dataReceiving = true;
                refreshChart(response);
            }else {
                $scope.dataReceiving = false;
            }


        });
    }
    //
    $interval(function () {
        requestData();
    },10000);
    // requestData();
    //
    //
    //
    var refreshChart = function (response) {
        $(function () {
            $('#graph-container').highcharts({
                chart: {
                    zoomType: 'x'
                },
                title: {
                    text: '实时数据频域图'
                },

                subtitle: {
                    text: '时间：' + response.time
                },
                xAxis: {
                    // type: 'datetime',
                    minRange: 11024  // fourteen days
                },
                yAxis: {
                    title: {
                        text: '幅值'
                    }
                    // minRange: 1e-5
                },
                legend: {
                    enabled: false
                },
                plotOptions: {
                    area: {
                        fillColor: {
                            linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1},
                            stops: [
                                [0, Highcharts.getOptions().colors[0]],
                                [1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]
                            ]
                        },
                        marker: {
                            radius: 2
                        },
                        lineWidth: 1,
                        states: {
                            hover: {
                                lineWidth: 1
                            }
                        },
                        threshold: null
                    }
                },
                series: [{
                    animation: false,
                    type: 'area',
                    name: '幅值',
                    pointInterval: 1,
                    pointStart: 0,
                    data: response.data1
                }]
            });
        });
    }
    //
    //
    // $('.form_date').datetimepicker({
    //     language:  'zh-CN',
    //     format: 'yyyy-MM-dd',
    //     weekStart: 1,
    //     todayBtn:  1,
    //     autoclose: 1,
    //     todayHighlight: 1,
    //     startView: 2,
    //     minView: 2,
    //     forceParse: 1
    // });
    //
    //
    //
    // $scope.imageName = '';
    //
    // $scope.save = function() {
    //     var fd = new FormData();
    //     var file = document.querySelector('input[type=file]').files[0];
    //     fd.append('logo', file);
    //     $http({
    //         method:'POST',
    //         url:"/file-upload",
    //         data: fd,
    //         headers: {'Content-Type':undefined},
    //         transformRequest: angular.identity
    //     })
    //         .success( function ( response )
    //         {
    //             //上传成功的操作
    //             console.log(response.logo.name);
    //             $scope.imageName =  response.logo.name;
    //             alert("上传成功");
    //         });
    //
    //
    // };
    //
    //








}]);
